//@ sourceURL=index.js

var IndexService = function () {
  var branches = ["master", "vNext", "live"];// TODO:  从服务器获取
  var clusterAttrs = [];// TODO:  从服务器获取
  var excludeAttrs = [];// TODO:  从服务器获取
  // 初始化添加属性时间 开始
  var index = 0;
  var params = {
    clusterAttrs:{
      node: "#clusterAttrs",
      addBtn: "#addcluster",
      delBtn: ".delCluster",
      data: clusterAttrs,
      initContent: function (data) {
        var html = '';
        for (var key in data) {
          if (data[key].clusterName && data[key].branch) {
            html +=
            '<div class="attr">'
              +'<label for="clusterName'+index+'">Cluster：</label>'
              +'<input type="text" id="clusterName'+index+'" value="'+data[key].clusterName+'" placeholder="输入集群名称">'
              +'<label for="branch'+index+'" style="margin-left: 50px;">Branch：</label>'
              +'<select id="branch'+index+'" style="width:80px;">'
              +'<option>选择分支</option>';
              for (var i in branches) {
                if (data[key].branch == branches[i]) {
                  html += '<option value="'+branches[i]+'" selected>'+branches[i]+'</option>';
                } else {
                  html += '<option value="'+branches[i]+'">'+branches[i]+'</option>';
                }
              }
              html +=
              '</select>'
              +'<button type="button" class="delCluster" style="margin-left: 30px;">－</button>'
              +'<span class="error-info" style="margin-left: 30px;font-size: 12px;color: red;"></span>'
              +'</div>';
          }
        }
        return html;
      },
      addContent: function () {
        var html = '<div class="attr">'
          +'<label for="clusterName'+index+'">Cluster：</label>'
          +'<input type="text" id="clusterName'+index+'" value="" placeholder="输入集群名称">'
          +'<label for="branch'+index+'" style="margin-left: 50px;">Branch：</label>'
          +'<select id="branch'+index+'" style="width:80px;">'
          +'<option>选择分支</option>';
          for (var i in branches) {
            html += '<option value="'+branches[i]+'">'+branches[i]+'</option>';
          }
          html +=
          '</select>'
          +'<button type="button" class="delCluster" style="margin-left: 30px;">－</button>'
          +'<span class="error-info" style="margin-left: 30px;font-size: 12px;color: red;"></span>'
          +'</div>';
         return html;
      }
    },
    excludeAttrs:{
      node: "#excludeAttrs",
      addBtn: "#addExclude",
      delBtn: ".delExclude",
      data: excludeAttrs,
      initContent: function (data) {
        var html = '';
        for (var key in data) {
          if (data[key].serverRole && data[key].apps) {
            html +=
            '<div class="attr">'
              +'<label for="serverRole'+index+'">ServerRole：</label>'
              +'<input type="text" id="serverRole'+index+'" value="'+data[key].serverRole+'" placeholder="serverRole">'
              +'<label for="apps'+index+'" style="margin-left: 50px;">App：</label>'
              +'<input type="text" id="apps'+index+'" value="'+data[key].apps+'" placeholder="多个用逗号分隔">'
              +'<button type="button" class="delExclude" style="margin-left: 30px;">－</button>'
              +'<span class="error-info" style="margin-left: 30px;font-size: 12px;color: red;"></span>'
             +'</div>';
          }
        }
        return html;
      },
      addContent: function () {
        var html = '<div class="attr">'
        +'<label for="serverRole'+index+'">ServerRole：</label>'
        +'<input type="text" id="serverRole'+index+'" value="" placeholder="serverRole">'
        +'<label for="apps'+index+'" style="margin-left: 50px;">App：</label>'
        +'<input type="text" id="apps'+index+'" value="" placeholder="多个用逗号分隔">'
        +'<button type="button" class="delExclude" style="margin-left: 30px;">－</button>'
        +'<span class="error-info" style="margin-left: 30px;font-size: 12px;color: red;"></span>'
       +'</div>';
       return html;
     }
    }
  };
  var clearErrorEvent = function () {
    $(document).on('change',".attr input,.attr select", function() {
      $(this).parent().find(".error-info").empty();
    });
  }
  var addAttr = function(node, content) {
     $(node).append(content);
     index++;
  };
  var delAttr = function (node) {
    $(node).parent().remove();
  };
  var initBtn = function (param) {
    if (param.data && param.data.length > 0) {
      addAttr(param.node, param.initContent(param.data));
    } else {
      addAttr(param.node, param.addContent());
    }
    $(document).on('click', param.addBtn, function() {
      addAttr(param.node, param.addContent());
    });
    $(document).on('click', param.delBtn, function() {
      delAttr(this);
    });
  };
  var initAttrAndExclude = function () {
    for (var key in params) {
      initBtn(params[key]);
    }
    clearErrorEvent();
  };
  // 初始化添加属性时间 结束

  var buildData = function () {
    var errorMessage;
    var data = $("#editConfigForm").serializeArray();
    var clusterAttrs = [];
    var excludeAttrs = [];
    $("#clusterAttrs .attr").each(function() {
      var clusterName = $(this).find("[id^=clusterName]").val();
      var branch = $(this).find("[id^=branch]").val();
      if (clusterName && branches.indexOf(branch) < 0) {
        errorMessage = "请选择对应分支";
        $(this).find(".error-info").html(errorMessage);
        return false;
      }
      if (!clusterName && branches.indexOf(branch) >= 0) {
        errorMessage = "请输入集群名称";
        $(this).find(".error-info").html(errorMessage);
        return false;
      }
      if (clusterName && branch && branches.indexOf(branch) >= 0) {
          clusterAttrs.push({"clusterName":clusterName, "branch":branch});
      }
    });
    //如果验证未通过，返回空
    if (errorMessage) {
        return null;
    }
    if (clusterAttrs && clusterAttrs.length > 0) {
        data.push({name: "clusterAttrs", value: JSON.stringify(clusterAttrs)});
    }

    $("#excludeAttrs .attr").each(function() {
      var serverRole = $(this).find("[id^=serverRole]").val();
      var apps = $(this).find("[id^=apps]").val();
      if (serverRole && !apps) {
        errorMessage = "请输入App";
        $(this).find(".error-info").html(errorMessage);
        return false;
      }
      if (!serverRole && apps) {
        errorMessage = "请输入ServerRole";
        $(this).find(".error-info").html(errorMessage);
        return false;
      }
      if (serverRole && apps) {
        excludeAttrs.push({"serverRole":serverRole, "apps":apps});
      }
    });
    //如果验证未通过，返回空
    if (errorMessage) {
      return null;
    }
    if (excludeAttrs && excludeAttrs.length > 0) {
        data.push({name: "excludeAttrs", value: JSON.stringify(excludeAttrs)});
    }
    return data;
  };
  var initSaveForm = function () {
    $("#editConfigForm").submit(function() {
      var data = buildData();
      if (!data) {
        return false;
      }
      console.log(data);
      return false;
      $.ajax({
        url: this.action,
        type: 'POST',
        dataType: 'json',
        data: data,
        success: function(result) {
          console.log(result);
        },
        error: function() {
          alert("出错了");
        }
      });
      return false;
    });
  }

  return  {
    initMain: function () {
      initAttrAndExclude();
      initSaveForm();
    }
  }
}();
